package cn.itcast.usermanage.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.abel533.entity.Example;
import com.github.abel533.entity.Example.Criteria;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.itcast.usermanage.mapper.NewUserMapper;
import cn.itcast.usermanage.mapper.UserMapper;
import cn.itcast.usermanage.pojo.EasyUIResult;
import cn.itcast.usermanage.pojo.User;
import cn.itcast.usermanage.service.UserService;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private NewUserMapper userMapper;

	/*@Override
	public EasyUIResult queryUsersByPage(Integer pageNum, Integer pageSize) {
		// 第一个参数是起始条数，第二个参数是每页的条数
		List<User> userList = this.userMapper.queryUsersByPage((pageNum-1)*pageSize, pageSize);
		Long total = this.userMapper.queryTotal();
		
		EasyUIResult easyUIResult = new EasyUIResult();
		easyUIResult.setRows(userList);
		easyUIResult.setTotal(total);
		
		return easyUIResult;
	}*/
	
	/**
	 * 使用分页插件--PageHelper分页查询用户信息
	 */
	@Override
	public EasyUIResult queryUsersByPage(Integer pageNum, Integer pageSize) {
		// 在查询方法调用之前，调用分页插件的静态方法，中间最好不要隔任何代码
		PageHelper.startPage(pageNum, pageSize);
		List<User> userList = this.userMapper.select(null);//查询全部
		
		// 初始化pageInfo对象，所有的分页参数都可以在该对象中获取
		PageInfo<User> pageInfo = new PageInfo<User>(userList);
		
		EasyUIResult easyUIResult = new EasyUIResult();
		easyUIResult.setTotal(pageInfo.getTotal());
		easyUIResult.setRows(pageInfo.getList());
		
		return easyUIResult;
	}

	@Override
	public void addUsers(User user1, User user2) throws Exception {
//		this.userMapper.addUser(user1);
		//制造异常，测试service的事务
//		int i = 1/0;
//		this.userMapper.addUser(user2);
		
	}

	@Override
	public Boolean addUser(User user) throws Exception {
		// 返回值count：操作数据库时成功的次数
		int count = this.userMapper.insertSelective(user);
		if (count > 0) {
			return true;
		}
		return false;
	}

	@Override
	public Boolean updateUser(User user) throws Exception {
/*		// 返回值count：操作数据库时成功的次数
		int count = this.userMapper.updateByPrimaryKey(user);
		if (count > 0) {
			return true;
		}
		return false;
*/
		return this.userMapper.updateByPrimaryKeySelective(user) > 0;
	}

	@Override
	public Boolean deleteUser(List<Object> ids) {
		Example example = new Example(User.class);
		Criteria criteria = example.createCriteria();
		criteria.andIn("id", ids); //andIn(String property, List<Object> values)
		
		int count = this.userMapper.deleteByExample(example);
		if (count > 0) {
			return true;
		}
		return false;
	}

	@Override
	public User queryUserById(Long id) {
		
		return this.userMapper.selectByPrimaryKey(id);
	}

	@Override
	public Boolean deleteUser(Long id) {
		return this.userMapper.deleteByPrimaryKey(id) > 0;
	}
	
	
}
